<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <el-row :gutter="24">
      <!-- 左侧：基本信息 -->
      <el-col :xs="24" :lg="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" size="small" @click="handleEdit">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
            </div>
          </template>
          
          <div class="profile-info">
            <div class="avatar-section">
              <el-avatar :size="80" :src="userInfo.userAvatar">
                {{ userInfo.userName?.charAt(0) }}
              </el-avatar>
              <div class="avatar-info">
                <h3>{{ userInfo.userName || '未设置昵称' }}</h3>
                <p class="user-role">{{ getRoleText(userInfo.userRole) }}</p>
                <p class="join-time">加入时间：{{ formatTime(userInfo.createTime) }}</p>
              </div>
            </div>
            
            <el-divider />
            
            <el-descriptions :column="2" border>
              <el-descriptions-item label="用户名">
                {{ userInfo.userAccount }}
              </el-descriptions-item>
              <el-descriptions-item label="昵称">
                {{ userInfo.userName || '未设置' }}
              </el-descriptions-item>
              <el-descriptions-item label="个人简介">
                {{ userInfo.userProfile || '这个人很懒，什么都没写~' }}
              </el-descriptions-item>
              <el-descriptions-item label="用户角色">
                <el-tag :type="getRoleTagType(userInfo.userRole)">
                  {{ getRoleText(userInfo.userRole) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatTime(userInfo.createTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="最后更新">
                {{ formatTime(userInfo.updateTime) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>

        <!-- 接口调用统计 -->
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>接口调用统计</span>
              <el-button type="text" size="small" @click="refreshStats">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ stats.totalCalls }}</div>
                <div class="stat-label">总调用次数</div>
                <div class="stat-trend">
                  <span class="trend-up">+{{ stats.todayCalls }}</span>
                  <span class="trend-text">今日</span>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ stats.successCalls }}</div>
                <div class="stat-label">成功调用</div>
                <div class="stat-rate">
                  成功率 {{ stats.successRate }}%
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ stats.favoriteInterfaces }}</div>
                <div class="stat-label">收藏接口</div>
                <div class="stat-trend">
                  <span class="trend-text">最近使用</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 右侧：积分和快捷操作 -->
      <el-col :xs="24" :lg="8">
        <!-- 积分余额 -->
        <el-card class="balance-card">
          <template #header>
            <div class="card-header">
              <span>积分余额</span>
              <el-button type="text" size="small" @click="showRecharge">
                充值
              </el-button>
            </div>
          </template>
          
          <div class="balance-info">
            <div class="balance-amount">
              <span class="currency">¥</span>
              <span class="amount">{{ balance.amount }}</span>
            </div>
            <div class="balance-details">
              <div class="detail-item">
                <span class="label">可用积分：</span>
                <span class="value">{{ balance.points }}</span>
              </div>
              <div class="detail-item">
                <span class="label">冻结积分：</span>
                <span class="value">{{ balance.frozenPoints }}</span>
              </div>
              <div class="detail-item">
                <span class="label">本月消费：</span>
                <span class="value">¥{{ balance.monthlySpent }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 快捷操作 -->
        <el-card class="quick-actions-card">
          <template #header>
            <span>快捷操作</span>
          </template>
          
          <div class="quick-actions">
            <el-button type="primary" class="action-btn" @click="goToInterfaceSquare">
              <el-icon><Connection /></el-icon>
              接口广场
            </el-button>
            <el-button type="success" class="action-btn" @click="goToMyInterfaces">
              <el-icon><List /></el-icon>
              我的接口
            </el-button>
            <el-button type="warning" class="action-btn" @click="goToCallHistory">
              <el-icon><Clock /></el-icon>
              调用历史
            </el-button>
            <el-button type="info" class="action-btn" @click="goToSettings">
              <el-icon><Setting /></el-icon>
              账户设置
            </el-button>
          </div>
        </el-card>

        <!-- 最近活动 -->
        <el-card class="recent-activity-card">
          <template #header>
            <span>最近活动</span>
          </template>
          
          <div class="activity-list">
            <div 
              v-for="activity in recentActivities" 
              :key="activity.id" 
              class="activity-item"
            >
              <div class="activity-icon">
                <el-icon :color="activity.color">
                  <component :is="activity.icon" />
                </el-icon>
              </div>
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-time">{{ activity.time }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人信息"
      width="500px"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <el-avatar v-if="editForm.userAvatar" :size="80" :src="editForm.userAvatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="userName">
          <el-input v-model="editForm.userName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="个人简介" prop="userProfile">
          <el-input
            v-model="editForm.userProfile"
            type="textarea"
            :rows="3"
            placeholder="请输入个人简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Edit, 
  Refresh, 
  Connection, 
  List, 
  Clock, 
  Setting, 
  Plus,
  User,
  Lock,
  Star
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userInfo = ref({
  userAccount: 'jair',
  userName: 'Jair',
  userAvatar: '',
  userProfile: '我是一个Java编程爱好者',
  userRole: 'admin',
  createTime: '2025-08-02 17:08:41',
  updateTime: '2025-08-05 20:47:34'
})

// 统计数据
const stats = ref({
  totalCalls: 1250,
  todayCalls: 23,
  successCalls: 1180,
  successRate: 94.4,
  favoriteInterfaces: 8
})

// 积分余额
const balance = ref({
  amount: '128.50',
  points: 1285,
  frozenPoints: 50,
  monthlySpent: '45.20'
})

// 最近活动
const recentActivities = ref([
  {
    id: 1,
    title: '调用了"今天天气怎么样"接口',
    time: '2分钟前',
    icon: 'Connection',
    color: '#409EFF'
  },
  {
    id: 2,
    title: '收藏了"用户信息查询"接口',
    time: '1小时前',
    icon: 'Star',
    color: '#E6A23C'
  },
  {
    id: 3,
    title: '更新了个人信息',
    time: '3小时前',
    icon: 'User',
    color: '#67C23A'
  },
  {
    id: 4,
    title: '修改了账户密码',
    time: '1天前',
    icon: 'Lock',
    color: '#F56C6C'
  }
])

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref()
const saving = ref(false)

const editForm = reactive({
  userName: '',
  userProfile: '',
  userAvatar: ''
})

const editRules = {
  userName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  userProfile: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取角色文本
const getRoleText = (role) => {
  const roleMap = {
    'admin': '管理员',
    'user': '普通用户',
    'ban': '封禁用户'
  }
  return roleMap[role] || '未知'
}

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    'admin': 'danger',
    'user': 'success',
    'ban': 'info'
  }
  return typeMap[role] || 'info'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 编辑信息
const handleEdit = () => {
  editForm.userName = userInfo.value.userName
  editForm.userProfile = userInfo.value.userProfile
  editForm.userAvatar = userInfo.value.userAvatar
  editDialogVisible.value = true
}

// 保存信息
const handleSave = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    saving.value = true
    
    // 模拟保存
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新用户信息
    userInfo.value.userName = editForm.userName
    userInfo.value.userProfile = editForm.userProfile
    userInfo.value.userAvatar = editForm.userAvatar
    userInfo.value.updateTime = new Date().toLocaleString('zh-CN')
    
    ElMessage.success('保存成功')
    editDialogVisible.value = false
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

// 头像上传
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  
  if (isJPG && isLt2M) {
    // 模拟上传
    const reader = new FileReader()
    reader.onload = (e) => {
      editForm.userAvatar = e.target.result
    }
    reader.readAsDataURL(file)
  }
  
  return false // 阻止自动上传
}

// 刷新统计
const refreshStats = () => {
  ElMessage.success('统计数据已刷新')
}

// 显示充值
const showRecharge = () => {
  ElMessage.info('充值功能开发中...')
}

// 快捷操作
const goToInterfaceSquare = () => {
  router.push('/interface')
}

const goToMyInterfaces = () => {
  router.push('/admin/interface')
}

const goToCallHistory = () => {
  ElMessage.info('调用历史功能开发中...')
}

const goToSettings = () => {
  router.push('/settings')
}

onMounted(() => {
  // 初始化用户信息
  if (userStore.userInfo) {
    Object.assign(userInfo.value, userStore.userInfo)
  }
})
</script>

<style scoped lang="scss">
.profile-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
  
  h2 {
    font-size: 28px;
    color: #303133;
    margin-bottom: 8px;
  }
  
  p {
    color: #909399;
    font-size: 14px;
  }
}

.profile-card {
  margin-bottom: 24px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .profile-info {
    .avatar-section {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      
      .avatar-info {
        margin-left: 20px;
        
        h3 {
          margin: 0 0 8px 0;
          font-size: 20px;
          color: #303133;
        }
        
        .user-role {
          color: #409EFF;
          font-weight: 500;
          margin: 0 0 4px 0;
        }
        
        .join-time {
          color: #909399;
          font-size: 12px;
          margin: 0;
        }
      }
    }
  }
}

.stats-card {
  margin-bottom: 24px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .stat-item {
    text-align: center;
    padding: 20px;
    
    .stat-number {
      font-size: 32px;
      font-weight: bold;
      color: #409EFF;
      margin-bottom: 8px;
    }
    
    .stat-label {
      color: #606266;
      font-size: 14px;
      margin-bottom: 8px;
    }
    
    .stat-trend {
      font-size: 12px;
      
      .trend-up {
        color: #67C23A;
        font-weight: 500;
      }
      
      .trend-text {
        color: #909399;
        margin-left: 4px;
      }
    }
    
    .stat-rate {
      color: #E6A23C;
      font-size: 12px;
      font-weight: 500;
    }
  }
}

.balance-card {
  margin-bottom: 24px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .balance-info {
    text-align: center;
    
    .balance-amount {
      margin-bottom: 20px;
      
      .currency {
        font-size: 24px;
        color: #909399;
      }
      
      .amount {
        font-size: 36px;
        font-weight: bold;
        color: #67C23A;
        margin-left: 4px;
      }
    }
    
    .balance-details {
      .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        
        .label {
          color: #606266;
        }
        
        .value {
          color: #303133;
          font-weight: 500;
        }
      }
    }
  }
}

.quick-actions-card {
  margin-bottom: 24px;
  
  .quick-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    .action-btn {
      justify-content: flex-start;
      height: 40px;
      
      .el-icon {
        margin-right: 8px;
      }
    }
  }
}

.recent-activity-card {
  .activity-list {
    .activity-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .activity-icon {
        margin-right: 12px;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
        border-radius: 50%;
      }
      
      .activity-content {
        flex: 1;
        
        .activity-title {
          color: #303133;
          font-size: 14px;
          margin-bottom: 4px;
        }
        
        .activity-time {
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }
}

.avatar-uploader {
  text-align: center;
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
  }
}

@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
    
    .avatar-info {
      margin-left: 0;
      margin-top: 16px;
    }
  }
  
  .stat-item {
    margin-bottom: 16px;
  }
  
  .quick-actions {
    .action-btn {
      width: 100%;
    }
  }
}
</style>
